<template>
  <div class="vertical">
    <div style="width:100%;position:relative;">
      <waveSufer :srcUrl="srcUrl" :callStatus="callStatus" @showOldAudio="showOldAudio" @callAllTimeLess='callAllTimeLess' :audioSpeed="audioSpeed" :wavesurferId="flagId" :isAutoPlay="isAutoPlay" ref="waveSuferRef" @pauseRecord='pauseRecord'></waveSufer>
      <div class="select-wrap" :class="callTimeLessFlag?'hide-select-wrap':''">
        <el-select v-if='isShowSelect' size="mini" style="margin-top: -9px;width: 90px" v-model="audioSpeed" class="audio-speed-wrap" :placeholder="$t('public.pleasePick')" @change="changeAudioSpeed">
          <el-option
                  v-for="(item, index) in audioSpeedArr"
                  :label="item.name"
                  :value="item.value"
                  :key="index"
                  >
          </el-option>
        </el-select>
        <span class="spanDowm">
          <a v-if='isShowAudioDownload && isDownload  && currentObj && currentObj.CALL_TIME_LENGTH > 0' class="call_sheet_download_file" :href="srcUrl" target="_blank" download><i style="font-size:18px;" class="el-icon-download"></i></a>
          <!--显示下载按钮  && 有下载录音的权限 && 通话时长大于0-->
          <a v-if='isConfig && isShowAudioDownload' class="call_sheet_download_file" :href="srcUrl" target="_blank" download><i style="font-size:18px;" class="el-icon-download"></i></a>
        </span>
        <submitRecord v-if="isShowSubmitAudio && isShowSubmitOrRevoke && currentObj && currentObj.STATUS === 'dealing' && recordShow" :currentObj="currentObj"></submitRecord>
        <span v-if="iscallDetail && showTran" class="spanDowm">
          <span @click="transText"><i class="iconfont icon-yuyinzhuanxie"></i> {{$t('call.voiceTranscription')}}</span>
        </span>
        <el-checkbox v-if="isCallGrade" v-model="audioIsAutoPlay" @change='isAutoPlayChange' size="mini">自动播放</el-checkbox>
        <div style="float:right" v-if="isShowMore">
          <span class="el-dropdown-link" @click="more">
            {{$t('call.more')}}<i v-show="!flag" class="el-icon-arrow-down el-icon--right"></i><i v-show="flag" class="el-icon-arrow-up el-icon--right"></i>
          </span>
        </div>
      </div>

    </div>
    <div v-if="count>0">
      <div v-show="flag" v-for="(item,index) of consultRecordArr" :key="index">
        <audio controls="" v-bind:src ="item.srcUrl" :id="'quality-autoplay_' + index" 
         class="audioShow"></audio>
        <div class="wave-detail-box">
          <i class="iconfont icon-baochi audio-icon" :class="item.isplay?'icon-huifu':''" @click="playOrPause(index)"></i>
          <span>{{item.timeStr}}</span>
          <span v-if="isHideTel" style="margin-left:20px">{{hideTel(item.workNoOrPhone)}}</span>
          <span class="spanDowm">
            <a v-if='isShowAudioDownload && isDownload  && currentObj && currentObj.CALL_TIME_LENGTH > 0' class="call_sheet_download_file" :href="item.srcUrl" target="_blank" download><i style="font-size:18px;" class="el-icon-download"></i></a>
            <!--显示下载按钮  && 有下载录音的权限 && 通话时长大于0-->
            <a v-if='isConfig && isShowAudioDownload' class="call_sheet_download_file" :href="srcUrl" target="_blank" download><i style="font-size:18px;" class="el-icon-download"></i></a>
            <!-- <span><i class="iconfont icon-yuyinzhuanxie"></i> 实时转写</span> -->
          </span>
        </div>
      </div>
    </div>


  </div>
</template>
<script>
  import {isHasFunc} from '@/utils/m7Utils.js'
  import waveSufer from './waveSufer'
  import submitRecord from './submitRecord.vue'
  import {getCallTimeLength,checkHideTel} from '@/utils/m7Utils.js'
  import { isHideTel } from '@/utils/customerUtils.js'
  let clearInter
  let timeNumber
  export default {
    name: 'audio1',
    data () {
      return {
        audioSpeed: '',
        audioSpeedArr: [
          {'name': this.$t('qualityCheck.zeroPointFiveAudioSpeed'), 'value': 0.5},
          {'name': this.$t('qualityCheck.zeroPointSeventAudioSpeed'), 'value': 0.75},
          {'name': this.$t('qualityCheck.oneAudioSpeed'), 'value': 1},
          {'name': this.$t('qualityCheck.onePointTwoAudioSpeed'), 'value': 1.25},
          {'name': this.$t('qualityCheck.onePointFiveAudioSpeed'), 'value': 1.5},
          {'name': this.$t('qualityCheck.onePointSeventAudioSpeed'), 'value': 1.75},
          {'name': this.$t('qualityCheck.twoAudioSpeed'), 'value': 2}
        ],
        isShowSubmitOrRevoke: false,
        callTimeLessFlag: false, // 录音时长是否<0
        showTran: true,
        audioIsAutoPlay: true,
        flag:false,
        count:0
      }
    },
    props: {
      iscallDetail: {type: Boolean, default: false}, // 只有通话详情展示语音转写
      flagId: {type: String, default: ''}, // 区分audio的id的标志
      srcUrl: {type: String, default: ''}, // audio地址
      refreshAudio: {type: Number, default: 0}, // 否要取本地音量和倍速的标志
      isShowAudioDownload: {type: Boolean, default: false}, // 是否要展示下载按钮 (默认是不展示)
      isDownload: {type: Boolean, default: false}, // 是否有权限下载录音
      changeStyle: {type: String, default: ''}, // 改变audio的样式
      currentObj: {
        type: Object,
        default: function () {
          return {}
        }
      }, // 当前的数据对象
      consultRecordArr: {
        type: Array,
        default: function () {
          return []
        }
      }, // 咨询录音
      isShowSubmitAudio: {type: Boolean, default: false}, // 是否要展示提交录音 (默认是不展示)
      isAutoPlay: {type: Boolean, default: true}, // 是否要自动播放 (默认是自动播放)
      isShowSelect: {type: Boolean, default: true}, // 是否要展示多倍速(默认是展示的)
      isShowMore: {type: Boolean, default: false}, // 是否要展示更多(默认是不展示的)
      isConfig: {type: Boolean, default: false}, // 是否是设置模块
      isCallGrade: {type: Boolean, default: false}, // 是否是质检模块
      recordShow: {type: Boolean, default: false}, // // 是否展示提交质检按钮（工单模块关联通话不展示）
      pauseAudio: String, // 关闭弹窗的时候，暂停录音
      callStatus: String,
    },
    components: {
      waveSufer,
      submitRecord
    },
    watch: {
      refreshAudio: 'refreshAudioes',
      pauseAudio (curr) {
        if (curr === 'close') {
          this.$refs.waveSuferRef.pauseAudio()
        }
      }
    },
    methods: {     
      hideTel (tel) {
        return checkHideTel(tel, this.$store.state.session.user)
      },
      showOldAudio (curr) {
        this.$emit('showOldAudio', curr)
      },
      callAllTimeLess (curr) {
        this.callTimeLessFlag = curr
      },
      changeAudioSpeed (item) {
        let local = window.localStorage
        local.setItem('audioSpeed', item)
        let myAudio = document.getElementById(this.flagId)
        if (myAudio && myAudio.playbackRate) {
          myAudio.playbackRate = item
        }
      },
      changeAudioVolume () {
        let myAudio = document.getElementById(this.flagId)
        if (myAudio) {
          window.localStorage.setItem('audioVolume', myAudio.volume)
          window.localStorage.setItem('audioMuted', myAudio.muted) // 静音状态
        }
      },
      refreshAudioes () {
        this.flag = false
        this.count = 0
        clearInterval(clearInter) // 去除定时器
        let localSpeed = window.localStorage.getItem('audioSpeed') - 0 || 1 // 多倍数
        let localVolume = window.localStorage.getItem('audioVolume')// 记忆音量
        let localMuted = window.localStorage.getItem('audioMuted') || 'false'// 记忆状态
        this.audioSpeed = localSpeed
        let slef = this
        this.$nextTick(function () { // 是为了处理又是watch被调用，但是audio的dom还没加载到的问题修复debugger
          let play = document.getElementById(slef.flagId)
          if (play) {
//            if (slef.isAutoPlay) { // 自动播放
//              play.play()
//            }
            if (play.playbackRate) {
              play.playbackRate = localSpeed || 1// 强制转化成数字
            }
            if (localVolume) {
              localVolume = parseFloat(localVolume)
            } else { // 被清除缓存或者是初始化
              localVolume = 1
            }
            play.volume = localVolume
            if (localMuted === 'false') {
              play.muted = false
            } else {
              play.muted = true
            }
          }
        })
      },
      transText () {
        this.$emit('transText')
      },
      //      已经评分
      graded () {
        this.$message.error(this.$t('call.yourCallMarked'))
      },
//      提交录音
      submitCallSheetRecordToQC (callSheetId, confirmed) {
        let data = {}
        data._id = callSheetId
        data.confirm = confirmed
        this.$store.dispatch('submitCallSheetRecordToQC', data).then(res => {
          if (res && res.success) {
            if (res.notifyToClient) {
              this.$confirm(res.message, this.$t('public.tip'), {
                confirmButtonText: this.$t('public.confirm'),
                cancelButtonText: this.$t('public.cancel'),
                cancelButtonClass: 'primary_btn',
                confirmButtonClass: 'primary_btn',
                type: 'warning'
              }).then(() => {
                this.submitCallSheetRecordToQC(callSheetId, true)
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: this.$t('call.cancelSubmitCallSheetRecordToQC')
                })
              })
            } else {
              let routeArry = this.$route.path.split('/')
              let tabType = routeArry[3]
              let QC_SUBMIT = true
              this.$store.commit('call/SET_QC_SUBMIT', {tabType, QC_SUBMIT})
              this.$message.success(this.$t('call.audioSubmitSuccess'))
            }
          }
        })
      },
      //      撤回录音
      revokeFromCallsSheetRecordQC (callSheetId, confirmed) {
        let data = {}
        data._id = callSheetId
        data.confirm = confirmed
        this.$store.dispatch('revokeFromCallsSheetRecordQC', data).then(res => {
          if (!res.success) {
            this.$message.error(res.message)
          } else {
            if (res.notifyToClient) {
              this.$confirm(res.message, this.$t('public.tip'), {
                confirmButtonText: this.$t('public.confirm'),
                cancelButtonText: this.$t('public.cancel'),
                cancelButtonClass: 'primary_btn',
                confirmButtonClass: 'primary_btn',
                type: 'warning'
              }).then(() => {
                this.revokeFromCallsSheetRecordQC(callSheetId, true)
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: this.$t('call.cancelRevokeFromCallsSheetRecordQC')
                })
              })
            } else {
              let routeArry = this.$route.path.split('/')
              let tabType = routeArry[3]
              let QC_SUBMIT = false
              this.$store.commit('call/SET_QC_SUBMIT', {tabType, QC_SUBMIT})
              this.$message.success(res.message)
            }
          }
        })
      },
      isAutoPlayChange (val) {
        this.$emit('isAutoPlaySet', val)
      },
      //更多
      more(){
        this.flag = !this.flag
        this.count = 1
        this.$nextTick(()=>{
          this.consultRecordArr.forEach((item,index)=>{
            let audioWrap = document.getElementById('quality-autoplay_' + index)
            if(this.count==0){
              audioWrap.load()
            }
            let self = this
            audioWrap.oncanplay = function () {
              self.$set(item,'currentTime',Math.round(audioWrap.currentTime || 0))
              self.$set(item,'allTime',Math.round(audioWrap.duration || 0))
              self.$set(item,'timeStr',self.getLastTime(item.currentTime, item.allTime))
            }
          })
        })
      },
      pauseRecord(flag){
        if(flag){
          this.consultRecordArr.forEach((item,index)=>{
            let audioWrap = document.getElementById("quality-autoplay_" + index)
            audioWrap.pause()
            if(!this.consultRecordArr[index].isplay){
              this.consultRecordArr[index].isplay = !this.consultRecordArr[index].isplay
            }
          })
        }
      },
      //播放与暂停
      playOrPause (index) {
        let audioWrap = document.getElementById("quality-autoplay_" + index)
        if(this.consultRecordArr[index].isplay){
          audioWrap.play()        
          this.$refs.waveSuferRef.pauseAudio()
          this.$refs.waveSuferRef.isplay = true
          this.consultRecordArr[index].isplay = !this.consultRecordArr[index].isplay
        }else{
          audioWrap.pause()
          this.consultRecordArr[index].isplay = !this.consultRecordArr[index].isplay
        }
        this.consultRecordArr.forEach((item,idx)=>{
          if(idx !== index){
            item.isplay = true
            let audioWrap1 = document.getElementById("quality-autoplay_" + idx)
            audioWrap1.pause()
          }
        })
        let step = 1
        if (this.audioSpeed === 0.5) {
          step = 0.8
          audioWrap.playbackRate=0.8
        } else if (this.audioSpeed === 0.75) {
          step = 0.9
          audioWrap.playbackRate=0.9
        } else if (this.audioSpeed === 1.25) {
          step = 1.2
          audioWrap.playbackRate=1.2
        } else if (this.audioSpeed === 1.5) {
          step = 1.3
          audioWrap.playbackRate=1.3
        } else if (this.audioSpeed === 1.75) {
          step = 1.5
          audioWrap.playbackRate=1.5
        } else if (this.audioSpeed === 2) {
          step = 1.6
          audioWrap.playbackRate=1.6
        } else {
          audioWrap.playbackRate=this.audioSpeed
        }
        timeNumber = Math.ceil(1000 / step)
        clearInterval(clearInter) // 去除定时器
        clearInter = setInterval(() => {
          this.consultRecordArr[index].currentTime = Math.round(audioWrap.currentTime || 0)
          this.consultRecordArr[index].timeStr = this.getLastTime(this.consultRecordArr[index].currentTime, this.consultRecordArr[index].allTime)
          if(audioWrap.ended){
            this.consultRecordArr[index].isplay=true
            this.getTimeStr()
            clearInterval(clearInter) // 去除定时器
          }
        }, timeNumber)
      },
      //处理时间
      getLastTime (time1, time2) {
        return getCallTimeLength(time1) + '/' + getCallTimeLength(time2)
      },
      //恢复初始值
      getTimeStr(){
        this.consultRecordArr.forEach((item,index)=>{
          let audioWrap = document.getElementById('quality-autoplay_' + index)
          if(audioWrap){
            item.currentTime = 0
            item.allTime = Math.round(audioWrap.duration || 0)
            item.timeStr = this.getLastTime(item.currentTime, item.allTime)
          }
        })
       
      },
      isHideTel () {
        return isHideTel(this.$store.state.session.user)
      }
    },
    beforeMount () {
      this.audioIsAutoPlay = this.$store.state.session.user.callRecordAutoPlay === false ? false : true
      this.refreshAudioes() // 初始化调用一次解决第一次渲染watch没有检测到变化的问题
      if (this.isShowSubmitAudio) { // 若显示提交/撤回录音 则去取一下权限
        if (isHasFunc('func_submit_to_quality_check', this.$store.state.session.user)) {
          this.isShowSubmitOrRevoke = true // 禁止提交或撤回录音等权限
        }
      }
      if (isHasFunc('func_hide_offline_transfer', this.$store.state.session.user)) {
        this.showTran = false // 隐藏实时转写
      }
      this.isHideTel()
    },
    beforeDestroy () {
      clearInterval(clearInter) // 销毁的时候去除定时器
    },
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl'
  a
    font-size: 12px
  .vertical
    align-items center
    padding 20px
    .audio-wrap
      display inline-block
      position relative
      /*top:10px*/
      /*margin:15px 10px 16px 10px*/

      .audio-speed-wrap
        width: 80px
        margin-right 12px
    .select-wrap
      margin 46px 0 0px 160px
    .hide-select-wrap
      display none
    .spanDowm
      margin-left: 8px
      a
        margin-right: 10px
      .iconfont,
      span
        color #FF8503
        cursor pointer
  .el-dropdown-link
    font-size: 12px
    cursor pointer
    color #409EFF
  .el-icon-arrow-down
    font-size: 12px
  .el-icon-arrow-up
    font-size: 12px
  .wave-detail-box
    margin-top 10px
    span
     display inline-block
     padding-top 3px
     line-height 16px
  .nouse-audio
    line-height 36px
  .audio-icon
    border 1px solid #459ae9
    border-radius 50%
    margin-right 6px
    margin-top 2px
    width 20px
    height 20px
    line-height 19px
    cursor pointer
    font-size 12px
    text-align center
    color #459ae9
    box-sizing border-box
    display inline-block
    float left
.audioShow
  visibility hidden
  position absolute
  top -9999px
  left -9999px
</style>
